#include "my_string.h"
//实现构造函数
//实现无参构造函数
String::String()
    :_pstr(new char[1]())
{
    //cout<<"String()"<<endl;
}

//有参构造
String::String(const char*str)
    :_pstr(new char[strlen(str)+1]())
{
    //cout<<"String(const char*)"<<endl;
    strcpy(_pstr,str);
}

//拷贝构造
String::String(const String & str)
    :_pstr(new char[strlen(str._pstr+1)]())
{
    //cout<<"String(const String &)"<<endl;
    strcpy(_pstr,str._pstr);
}

//实现析构函数
String::~String(){
    // cout<<"~String"<<endl;
    if(_pstr){
        delete []_pstr;
        _pstr = nullptr;
    }
}

//实现赋值运算符函数
String &String::operator=(const String &rhs){
    if(this != &rhs){
        delete []_pstr;
        _pstr = new char[strlen(rhs._pstr)+1]();
        strcpy(_pstr,rhs._pstr);
    }
    return *this;
}

String &String::operator=(const char *str){
    delete[]_pstr;
    if(str){
        _pstr = new char[strlen(str)+1]();
        strcpy(_pstr,str);
    }
    return *this;
}

//实现+=赋值运算符
String &String::operator+=(const String & rhs){
    char *temp = new char[strlen(_pstr)+strlen(rhs._pstr)+1]();
    strcpy(temp,_pstr);
    strcat(temp,rhs._pstr);
    delete []_pstr;
    _pstr = temp;
    return *this;
}

String &String::operator+=(const char*str){
    String temp(str);
    return *this+=temp;
}
//实现下标运算符重载
//可修改非常量版本
char &String:: operator[](std::size_t index){
    //需自己判断是否越界
    return _pstr[index];
}

//不可修改常量版本
const char &String:: operator[](std::size_t index) const{
    //需自己判断是否越界
    return _pstr[index];
}

//二者皆有初始化所以不需要考虑边界条件
//获得字符串有效长度
std::size_t String::size()const{
    return strlen(_pstr);
}

//返回c风格字符串
const char* String::c_str()const{
    return _pstr;
}

//实现各个判断运算符重载
bool operator==(const String &lhs,const String &rhs){
    return strcmp(lhs._pstr,rhs._pstr)==0;
}

bool operator!=(const String &lhs,const String &rhs){
    return !(lhs==rhs);
}

bool operator<(const String &lhs,const String &rhs){
    return strcmp(lhs._pstr,rhs._pstr)<0;
}

bool operator>(const String &lhs,const String &rhs){
    return rhs<lhs;
}

bool operator<=(const String &lhs,const String &rhs){
    return !(rhs<lhs);
}

bool operator>=(const String &lhs,const String &rhs){
    return !(lhs<rhs);
}

//实现+运算符重载
String operator+(const String &lhs, const String &rhs){
    String result(lhs);
    result+=rhs;
    return result;
}

String operator+(const String &lhs, const char *rstr){
    String result (lhs);
    if(rstr){
        result+=rstr;
    }
    return result;
}

String operator+(const char *lstr, const String &rhs){
    String result(lstr?lstr:"");
    result +=rhs;
    return result;
}

//实现输入输出运算符重载
std::ostream & operator<<(std::ostream &os,const String &s){
    os<<s._pstr;
    return os;
}

std::istream & operator>>(std::istream &is, String &s){
    if(s._pstr){
        delete []s._pstr;
    }

    std::string buf;    
    is>>buf;
    s._pstr = new char[buf.size()+1]();
    strcpy(s._pstr,buf.c_str());
    return is;
}







